<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;

use app\admin\model\CarModel;
use app\admin\model\College;
use app\api\model\AccessTokenModel;
use app\api\model\DouYinService;
use app\api\model\Token;
use app\common\model\AliPay;
use app\common\model\RebateLog;
use EasyWeChat\Factory;
use think\Exception;
use think\facade\Db;
use think\Model;


class DouyinModel extends Model
{
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;

    protected $table = 'yzn_douyin';

    public function staff()
    {
        return $this->belongsTo(StaffModel::class, 'uid', 'id')->setEagerlyType(0);
    }


    public function loginOut($params)
    {
        $token = \think\Db::name('user_token')->where(['user_id' => $params['uid']])->delete();
        if ($token) {
            return ['code' => 200, 'msg' => '退出成功', 'data' => []];
        }
        return ['code' => 201, 'msg' => '退出失败'];
    }


    public function dyLogin($params = array())
    {
        try {
            if (!$params['code']) {
                throw new Exception('缺少code');
            }
            $douyinService = (new DouYinService());
            $res = $douyinService->access_token($params['code']);
            if (!$res) {
                throw new Exception('登陆失败，请重新尝试');
            }
            $openid = $res['data']['open_id'];
            $access_token = $res['data']['access_token'];
            $refresh_token = $res['data']['refresh_token'];
            $expires_in = $res['data']['expires_in'];
            $refresh_expires_in = $res['data']['refresh_expires_in'];
            \think\Db::startTrans();
            $douyin = DouyinModel::where('openid', $openid)->field('id,nickname,avatar,status,mark')->find();
            $time = time();
            if (!$douyin) {
                $userInfo = $douyinService->getUserInfo($access_token, $openid);
                $data = [
                    'uid' => $params['uid'],
                    'openid' => $openid,
                    'nickname' => $userInfo['data']['nickname'],
                    'avatar' => $userInfo['data']['avatar'],
                    'create_time' => $time,
                    'update_time' => $time
                ];
                $douyinId = \think\Db::name('douyin')->insertGetId($data);
            } else {
                if ($douyin->status == 0) {
                    throw new Exception('账号已被封禁，暂时无法登陆');
                }
                $douyinId = $douyin->id;
                if($douyin->mark == 1) {
                    \think\Db::name('douyin')->where(['id' => $douyinId])->update(['mark' => 0]);
                }
                \think\Db::name('douyin')->where(['id' => $douyinId])->update(['update_time' => $time]);

            }

            //更新access_token
            $accessTokenLog = (new AccessTokenModel())->accessTokenLog($douyinId, $access_token, $expires_in, $refresh_token, $refresh_expires_in);
            if (!$accessTokenLog) {
                throw new Exception('登陆失败，请重新尝试1');
            }
            \think\Db::commit();

            return ['code' => 200, 'msg' => '添加成功', 'data' => $douyinId];

        } catch (Exception $e) {
            \think\Db::rollback();
            return ['code' => 201, 'msg' => $e->getMessage(), 'data' => []];
        }

    }


    public function getDyAccount($params = array())
    {
        $list = self::where(['uid' => $params['uid'],'mark' =>0])->field('avatar,nickname,id,status')->select();
        return ['code' => 200, 'msg' => '获取成功', 'data' => $list];
    }

    public function delDy($params){
        if(!$params['dy_id']){
            return ['code' => 201, 'msg' => "缺少参数", 'data' => []];
        }

        if(!self::where(['id' => $params['dy_id']])->update(['mark' => 1])){
            return ['code' => 201, 'msg' => "删除失败", 'data' => []];
        }

        return ['code' => 200, 'msg' => '删除成功', 'data' =>''];
    }

}
